﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using WorkflowCore.Primitives;
using WorkflowCore.Service.Dto.Fundamentals;
using WorkflowCore.Service.Persisted;

namespace WorkflowCore.Service.Steps
{
    /// <summary>
    /// 审核人
    /// </summary>
    public class PersonForeach:ContainerStepBody
    {
        private readonly WorkflowCoreDbcontext _dbcontext;
        private readonly GetWorkflowCoreUserData getWorkflowCoreUserData;

        public PersonForeach(WorkflowCoreDbcontext dbcontext, GetWorkflowCoreUserData getWorkflowCoreUserData)
        {
            _dbcontext = dbcontext;
            this.getWorkflowCoreUserData = getWorkflowCoreUserData;
        }
        /// <summary>
        /// 操作人员名单
        /// </summary>
        public string Collection {  get; set; }
        /// <summary>
        /// 是否并行
        /// </summary>
        public bool RunParallel {  get; set; }
        public override ExecutionResult Run(IStepExecutionContext context)
        {
            var userIdList = JsonConvert.DeserializeObject<List<long>>(Collection);
            if (context.PersistenceData == null)
            {
                var instance = _dbcontext.persistedWorkflowInstance.FirstOrDefault(p => p.WorkflowInstanceId == context.Workflow.Id);
                List<PersonNode> Users = getWorkflowCoreUserData.ShoWorkflowCoreUserData();
                var userNames = string.Join(',', Users.Where(p => userIdList.Contains(p.UserId)).Select(p => p.UserName));
                instance.CurrentAuditUserIds=string.Join(",", userIdList);
                instance.CurrentAuditUsers=userNames;
                instance.CurrentStepId = context.Step.ExternalId;
                instance.CurrentStepName= context.Step.Name;
                _dbcontext.SaveChanges();
                var values=userIdList.Cast<object>().ToList();
                if (!values.Any())
                {
                    return ExecutionResult.Next();
                }
                if (RunParallel)
                {
                    return ExecutionResult.Next();
                }
                else
                {
                    return ExecutionResult.Branch(new List<object>(new object[] { values.ElementAt(0) }),
                        new IteratorPersistenceData { ChildrenActive = true });
                };
            }
            if (context.PersistenceData is IteratorPersistenceData persistenceData && persistenceData?.ChildrenActive == true)
            {
                if (context.Workflow.IsBranchComplete(context.ExecutionPointer.Id))
                {
                    if (!RunParallel)
                    {
                        var values = userIdList.Cast<object>();
                        persistenceData.Index++;
                        if (persistenceData.Index < values.Count())
                        {
                            return ExecutionResult.Branch(new List<object>(new object[] { values.ElementAt(persistenceData.Index) }), persistenceData);
                        }
                    }
                    return ExecutionResult.Next();
                };
                return ExecutionResult.Persist(persistenceData);
            }
            if (context.PersistenceData is ControlPersistenceData controlPersistenceData && controlPersistenceData?.ChildrenActive == true)
            {
                if (context.Workflow.IsBranchComplete(context.ExecutionPointer.Id))
                {
                    return ExecutionResult.Next();
                }
            }
            return ExecutionResult.Persist(context.PersistenceData);
        }
    }
}
